/*
 * 文 件 名:  FileManager.java
 * 版    权:  Shenzhen Coship Electronics Co.,Ltd. Copyright YYYY-YYYY,  All rights reserved
 * 描    述:  <描述>
 * 修 改 人:  907009
 * 修改时间:  2014年4月11日
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */

package com.zhongketech.sunflower.utils;

import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 文件管理员。负责文件的读写
 * 
 * @author 907009
 * @version [版本号, 2014年4月11日]
 * @since [产品/模块版本]
 */
public class FileManager {

    private static final String TAG = "FileManager";

    private final static String BAK = ".bak";

    public static String readJsonData(String filePath) {

        File text = new File(filePath);
        if (!text.exists()) {
            return null;
        }
        StringBuffer sBuffer = new StringBuffer();
        String line = null;
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(
                    new FileInputStream(text)));

            while (null != (line = bufferedReader.readLine())) {
                sBuffer.append(line);
            }
        } catch (Exception e) {
            ILog.e(TAG, "readJsonData error ===> : " + e.getMessage());
        } finally {
            try {
                bufferedReader.close();
            } catch (Exception e) {
                ILog.e(TAG, e.getMessage());
            }
        }
        return sBuffer.toString();
    }

    public static boolean writeJsonData(String filePath, String data) {

        if (TextUtils.isEmpty(data) || TextUtils.isEmpty(filePath)) {
            return false;
        }

        // 采用临时文件避免正在读写文件时断电保存一份无用数据
        String tempFilePath = filePath + BAK;
        File tempFile = new File(tempFilePath);
        if (tempFile.exists()) {
            tempFile.delete();
        }
        FileOutputStream fos = null;
        boolean success = false;

        if (tempFile != null) {
            try {
                fos = new FileOutputStream(tempFile);
                fos.write(data.getBytes());
            } catch (Exception e) {
                ILog.e(TAG, "writeJsonData error : " + e.getMessage());
            } finally {
                try {
                    if (fos != null) {
                        fos.close();
                        success = true;
                    }
                } catch (IOException e) {
                    ILog.e(TAG, "writeJsonData io error : " + e.getMessage());
                }
            }
        }
        if (success) {
            File saveFile = new File(filePath);
            // 下载成功，更改名称
            if (saveFile.exists()) {
                saveFile.delete();
            }
            tempFile.renameTo(saveFile);
        }

        return success;
    }

    public static boolean clearFiles(String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return false;
        }

        File fileParent = new File(fileName);
        if (!fileParent.exists()) {
            return false;
        }
        ILog.i(TAG, "clearFile : " + fileName);
        File[] files = fileParent.listFiles();
        // 清除文件夹中内容
        if (null == files) {
            return true;
        }

        for (File file : files) {
            if (file.isDirectory()) {
                clearFiles(file.getPath());
            } else {
                file.delete();
            }
        }

        files = fileParent.listFiles();
        // 清除空的文件夹
        for (File file : files) {
            if (!file.isDirectory()) {
                continue;
            }

            if (0 == file.listFiles().length) {
                file.delete();
            }
        }
        return true;
    }

    public static void clearFile(String path) {
        File root = new File(path);
        if (!root.exists()) {
            return;
        }

        File[] files = root.listFiles();
        for (File f : files) {
            if (f.isDirectory()) {
                clearFile(f.getPath());
            }

            f.delete();
        }
    }

    /**
     * 根据byte[]生成文件
     */
    public static boolean toFile(byte[] bfile, String filePath, String fileName) {
        FileOutputStream fos = null;
        try {
            File dir = new File(filePath);

            // 判断文件目录是否存在
            if (!dir.exists()) {
                dir.mkdirs();
            }

            File file = new File(filePath, fileName);
            fos = new FileOutputStream(file);
            fos.write(bfile);
            fos.flush();

            return true;
        } catch (Exception e) {
            ILog.e(TAG, e.getMessage());
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    ILog.e(TAG, e.getMessage());
                }
            }
        }

        return false;
    }

    /**
     * 海报（posterUrl）是否在本地文件中
     */
    public static boolean isIntactWithImg(String cache, String posterUrl) {
        if (TextUtils.isEmpty(posterUrl)) {
            return false;
        }
        StringBuffer buffer = new StringBuffer();
        buffer.append(cache);
        buffer.append(File.separator);
        buffer.append(HashKeyTool.hashKeyForDisk(posterUrl));

        String localImgPath = buffer.toString();

        File imgFile = new File(localImgPath);
        // 海报文件不存在
        if (!imgFile.exists()) {
            return false;
        }
        // 海报文件存在，但是图片不完整，则删除该图片
        if (!isIntact(localImgPath)) {
            imgFile.delete();
            return false;
        }
        return true;
    }

    /**
     * 图片是否损坏 返回true：图片损坏
     */
    public static boolean isIntact(String imagePath) {
        Options opt = new Options();
        opt.inJustDecodeBounds = true;

        BitmapFactory.decodeFile(imagePath, opt);
        int width = opt.outWidth;
        int height = opt.outHeight;

        return width > 0 && height > 0;
    }

    /**
     * 图片是否损坏 返回true：图片损坏
     */
    public static boolean isIntact(byte[] bytes) {
        if (null == bytes) {
            return false;
        }
        Options opt = new Options();
        opt.inJustDecodeBounds = true;

        BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opt);
        int width = opt.outWidth;
        int height = opt.outHeight;

        return width > 0 && height > 0;
    }

    public static boolean isExsits(String path, String name) {
        File fileParent = new File(path);
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }

        File file = new File(path + name);
        if (file.exists()) {
            return true;
        }
        return false;
    }

}
